package com.xiaoc.bulldozer.controller;

import com.xc.framework.common.oss.AliOSS;
import com.xc.framework.common.utils.DateUtil;
import com.xiaoc.bulldozer.common.ResponseCode;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/image")
public class ImageController extends AdminBaseController {

    public static final Logger logger = LoggerFactory.getLogger(ImageController.class);

    @Resource
    private AliOSS aliOss;

    @Value("${oss.image.domain}")
    private String ossDomain;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView upload(@RequestParam("file") MultipartFile file) {

        if (file == null) {
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "上传文件不能为空");
        }

        String fileUrl = "";
        String filePath = "";

        try {
            InputStream inputStream = file.getInputStream();
            String name = file.getOriginalFilename();
            String suffix = StringUtils.substringAfterLast(name, ".");

            if (!StringUtils.equalsIgnoreCase(suffix, "jpg") && !StringUtils.equalsIgnoreCase(suffix, "jpeg") && !StringUtils.equalsIgnoreCase(suffix, "gif") && !StringUtils.equalsIgnoreCase(suffix, "png")) {
                return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "图片格式错误");
            }

            long currentTime = System.currentTimeMillis();

            String folder = DateUtil.formatDate(new Date(), "yyyyMMdd");
            String imageName = folder + "/" + currentTime + "." + suffix;
//            String folder = "material";
//            String imageName = folder + File.separator + name;
            filePath = "/" + imageName;

            aliOss.uploadFileInputStream(imageName, inputStream);
            fileUrl = ossDomain + imageName;
        } catch (Exception e) {
            logger.error("上传图片错误", e);
            return jsonFailed(ResponseCode.BUSINESS_ERROR.getCode(), "上传文件错误");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("filePath", filePath);
        paramMap.put("fileUrl", fileUrl);
        return renderJson("image/upload.json", paramMap);
    }
}
